from app.utils.log_core import LogCore, UILogger
import inspect
import traceback
import threading

class UILog:
    _log_open = False
    lock_1 = None
    def __init__(self, name: int, log_enable = True):
        self.name = name
        self.log_enable = log_enable
        if not UILog._log_open:
            UILog.Open()
    @staticmethod  
    def get_lock_1():
        if UILog.lock_1 is None:
            UILog.lock_1 = threading.Lock() 
        return UILog.lock_1

    
    @staticmethod
    def Open(enable_console: bool = False) :
        UILog._log_open = True
        UILogger.Open(enable_console,keep_file_cnt=50)
        UILog.lock_1 = UILog.get_lock_1()

    @staticmethod
    def INFO(msg : str):
        UILogger.Info(msg)

    @staticmethod
    def WARN(msg : str):
        UILogger.Warn(msg)
        
    @staticmethod
    def DEBUG(msg : str):
        UILogger.Debug(msg)
        
    @staticmethod
    def ERROR(msg : str):
        
        # 获取调用该函数的上一层栈帧
        frame = inspect.currentframe().f_back
        # 提取当前帧的信息（文件名、行号等）
        frame_info = inspect.getframeinfo(frame)
        
        # 如果当前调用者是类中的方法，则获取类名
        cls_name = ""
        if "self" in frame.f_locals:
            cls_name = frame.f_locals["self"].__class__.__name__
        
        # 获取调用栈的完整轨迹（从调用处开始的堆栈）
        stack_trace = "".join(traceback.format_stack(frame))
        
        # 构造完整的日志信息，包含名称、类名、文件和行号以及调用栈轨迹
        log_message = (
            f"[{cls_name}] "                       # 类名（如果有）
            f"[{frame_info.filename}:{frame_info.lineno}] "  # 文件名和行号
            f"{msg}\n"
            f"Traceback (most recent call last):\n{stack_trace}"
        )
        UILogger.Error(log_message)